/**
 * 文件描述如下：
 * 1. 鼠标在画布中点击时触发
 * 2. 用鼠标按下事件代理
 * 3. 防止用户点击的bug
 * 4.
 */
import { disposeObject } from "/src/utils/dispose.js";
let firstPointX, firstPointY, flage, store, keyboard;
import { mainStore } from "@store";

/**
 *
 * @method 鼠标在画布中点击时触发
 * @return 无
 *
 */
export const canvasMouseDown = (e) => {
  store = mainStore();
  firstPointX = e.pageX;
  firstPointY = e.pageY;
  flage = true;

  // 绑定鼠标移动和弹起事件处理
  document.addEventListener("mousemove", canvasMouseMove);
  document.addEventListener("mouseup", canvasMouseUp);
};

const canvasMouseMove = (e) => {
  // 当你都小于5时 默认你没移动
  if (
    Math.abs(e.pageX - firstPointX) < 5 &&
    Math.abs(e.pageY - firstPointY) < 5
  ) {
    flage = true;
  } else {
    flage = false;
  }
};

window.oldModel = null; // 选中的模型的旧数据
const canvasMouseUp = (e) => {
  // 先移除绑定事件
  document.removeEventListener("mousemove", canvasMouseMove);
  document.removeEventListener("mouseup", canvasMouseUp);

  if (flage) {
    // 发起射线
    const container = document
      .getElementById("webgl-perceivedEffect")
      .getBoundingClientRect();
    const params = {
      x: e.clientX - container.left,
      y: e.clientY - container.top,
      w: container.width,
      h: container.height,
    };

    let model = window.checkRaycastToCarBox(e, params);

    // 说明点击的是线框 则直接加载mesh 隐藏当前线框就行
    if (model && !model.syboml) {
      model.visible = false;
     if(window.oldModel) window.oldModel.visible = true
      window.oldModel = model;

      window.mesh.visible = true;
      window.mesh.carId = model.carId;
      window.mesh.position.copy(model.position);
      window.mesh.rotation.copy(model.rotation);

      // 将框线赋予颜色
      
      const color = filterColor(model?.label, store)
      window.mesh.material.color.set(color)
      store.currentCarId = model.carId;
      model.carId = "";
    }

    // 说明点击的是 mesh
    if (model && model.syboml) {
      window.oldModel.carId = model.carId;
      window.oldModel.visible = true;

      store.currentCarId = null;
      window.mesh.visible = false;
      window.mesh.carId = "";
      window.mesh.position.set(0, 0, 0);
    }
  }
};


 const filterColor = (type, store) => {
  let color = '#ffffff'
  const params = store.carTypeColor.find((element) => element.type == type)
  if (params) color = params.color

  return color
}
